package com.xg.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.xg.util.export.SheetData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelTemplateExporter {

    private static final Logger logger = LoggerFactory.getLogger(ExcelTemplateExporter.class);
    public static void exportWithTemplate(String templateName,
                                          String fileExportName,
                                          List<SheetData<?>> sheetDataList) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        InputStream templateStream = null;
        ExcelWriter excelWriter = null;

        try {
            String templatePath = "export/" + templateName;
            ClassPathResource resource = new ClassPathResource(templatePath);
            if (!resource.exists()) {
                logger.info("错误：模板文件不存在，路径为：" + templatePath);
                return;
            }
            templateStream = resource.getInputStream();

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileExportName, StandardCharsets.UTF_8.toString()));
            ServletOutputStream out = response.getOutputStream();

            FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
            excelWriter = EasyExcel.write(out).withTemplate(templateStream).build();

            for (SheetData<?> sheetData : sheetDataList) {
                String sheetName = sheetData.getSheetName();
                List<?> dataList = sheetData.getDataList();
                Class<?> entityClass = sheetData.getEntityClass();
                Map<String, Object> headerData = sheetData.getHeaderData();

                Map<Class<?>, List<?>> classDataMap = new HashMap<>();
                classDataMap.put(entityClass, dataList);

                WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
                        .registerWriteHandler(new ExcelTemplateStyleHandler<>(classDataMap))
                        .build();

                // 写入表头数据（可选）
                if (headerData != null && !headerData.isEmpty()) {
                    excelWriter.fill(headerData, writeSheet);
                }

                // 写入实体数据
                if (!dataList.isEmpty()) {
                    if (dataList.get(0) instanceof Map) {
                        excelWriter.fill(dataList, writeSheet);
                    } else {
                        excelWriter.fill(dataList, fillConfig, writeSheet);
                    }
                }
            }

        } catch (IOException e) {
            logger.info("导出异常: {}", e.getMessage());
        } finally {
            try {
                if (excelWriter != null) {excelWriter.finish();}
            } catch (Exception ignored) {}
        }
    }

}
